package ae.generator;

import oracle.jdbc.datasource.impl.OracleDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author: zxm
 * @date: 2025/9/4
 */
public class OracleConnection {

    /***
     * 获取元空间
     */
    public DatabaseMetaData getDatabaseMetaData(String propertiesName){
        try {
            Properties props = readJdbcConfig(propertiesName);
            Connection conn = getConnection(props.getProperty("oracle.url"), props.getProperty("oracle.username"), props.getProperty("oracle.password"));
            return conn.getMetaData();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取配置文件
     */
    private Properties readJdbcConfig(String propertiesName){
        try {
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propertiesName);
            if (inputStream == null) {
                throw new IOException(String.format("未找到%s文件，请确认文件在src/main/resources目录下",propertiesName));
            }
            Properties properties = new Properties();
            properties.load(inputStream);
            return properties;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 数据库连接
     */
    private Connection getConnection(String databaseUrl, String userName, String password) {
        try {
            var connectionProperties = new Properties();
            connectionProperties.setProperty(oracle.jdbc.driver.OracleConnection.CONNECTION_PROPERTY_USER_NAME, userName);
            connectionProperties.setProperty(oracle.jdbc.driver.OracleConnection.CONNECTION_PROPERTY_PASSWORD, password);
            var oracleDataSource = new OracleDataSource();
            oracleDataSource.setConnectionProperties(connectionProperties);
            oracleDataSource.setURL(databaseUrl);
            return oracleDataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
